<script setup>
import ThirdPlatformSession from '@core/engine/ThirdPlatform/Session';
import PageContainer from '@core/components/PageContainer.vue';
import LogoCtRed from '@/assets/logo.ctyun.red.svg';

const $router = useRouter();
const { t } = useI18n({ inheritLocale: true, useScope: 'local' });

const loginFormRef = ref();
const loginForm = reactive({ username: '', password: '' });
const isLoginSubmitting = ref(false);
const loginFormRules = reactive({
  username: [{ required: true, message: t('inputUsernamePlease'), trigger: 'blur' }],
  password: [{ required: true, message: t('inputPasswordPlease'), trigger: 'blur' }],
});
const onSubmitToLogin = async (formRef) => {
  if (!formRef) { return; }
  isLoginSubmitting.value = true;
  try {
    await formRef.validate();
    await ThirdPlatformSession.login(loginForm);
    // TODO: login 后应当跳转到登录前的页面
    $router.push({ name: 'home.index' });
  } catch (error) {
    isLoginSubmitting.value = false;
    throw error;
  }
};

onBeforeUnmount(() => {
  isLoginSubmitting.value = false;
});
</script>

<template>
  <PageContainer class="container">
    <LogoCtRed class="logo" width="125" height="125" viewBox="0 0 100 24" />
    <ElForm
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginFormRules"
      label-position="right"
      label-width="120px"
      status-icon
      class="login-form"
    >
      <ElFormItem :label="t('username')" prop="username">
        <ElInput v-model="loginForm.username" />
      </ElFormItem>
      <ElFormItem :label="t('password')" prop="password">
        <ElInput v-model="loginForm.password" type="password" show-password />
      </ElFormItem>
      <div class="footer">
        <ElButton
          class="login"
          type="primary"
          :loading="isLoginSubmitting"
          @click="onSubmitToLogin(loginFormRef)"
        >
          {{ t('login') }}
        </ElButton>
      </div>
    </ElForm>
  </PageContainer>
</template>

<i18n lang="yaml" locale="zh-CN">
  username: '用户名'
  password: '密码'
  login: '登录'
  inputUsernamePlease: '请输入用户名'
  inputPasswordPlease: '请输入密码'
</i18n>

<style lang="scss" scoped>
.container {
  flex-direction: column;
  align-items: center;
  background-color: #f0f2f5;
}

.logo {
  margin: 18vh auto 32px;
}

.login-form {
  width: 368px;
  margin-right: 108px;

  .footer {
    padding-left: 120px;

    .login {
      width: 100%;
    }
  }
}
</style>
